package com.wgz.flag.service.impl;

import com.wgz.flag.domain.dto.GroupMessageDTO;
import com.wgz.flag.domain.vo.GroupMessageVO;
import com.wgz.flag.entity.GroupMember;
import com.wgz.flag.entity.GroupMessage;
import com.wgz.flag.exception.BaseException;
import com.wgz.flag.mapper.GroupMemberMapper;
import com.wgz.flag.mapper.GroupMessageMapper;
import com.wgz.flag.service.GroupMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群聊消息服务实现类
 * 处理群聊消息的发送、撤回、历史记录等功能
 */
@Service
@RequiredArgsConstructor
public class GroupMessageServiceImpl implements GroupMessageService {

    private final GroupMessageMapper groupMessageMapper;
    private final GroupMemberMapper groupMemberMapper;

    /**
     * 发送群聊消息
     * 1. 检查发送者权限（是否是群成员、是否被禁言）
     * 2. 保存消息
     * 3. 返回消息详情
     */
    @Override
    public GroupMessageVO sendMessage(Long senderId, GroupMessageDTO messageDTO) {
        // 检查发送者是否是群成员且未被禁言
        GroupMember sender = groupMemberMapper.selectByGroupAndUserId(messageDTO.getGroupId(), senderId);
        if (sender == null || sender.getStatus() == 0) {
            throw new BaseException("您不是群成员");
        }

        // 检查是否被禁言
        if (sender.getStatus() == 2) {
            if (sender.getMuteEndTime() == null || sender.getMuteEndTime().isAfter(LocalDateTime.now())) {
                throw new BaseException("您已被禁言");
            } else {
                // 禁言时间已过，恢复正常状态
                groupMemberMapper.updateStatus(messageDTO.getGroupId(), senderId, 1);
            }
        }

        // 创建消息
        GroupMessage message = new GroupMessage();
        BeanUtils.copyProperties(messageDTO, message);
        message.setType(messageDTO.getContentType());
        message.setStatus(1);
        message.setSendTime(LocalDateTime.now());

        groupMessageMapper.insert(message);

        return convertToVO(groupMessageMapper.selectById(message.getId()));
    }

    @Override
    public List<GroupMessageVO> getMessageHistory(Long groupId, Long lastMessageId) {
        // 检查是否是群成员
        List<GroupMessage> messages = groupMessageMapper.getHistory(groupId, lastMessageId);
        return messages.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 撤回群聊消息
     * 1. 检查撤回权限
     * 2. 检查撤回时间限制
     * 3. 更新消息状态
     */
    @Override
    public void recallMessage(Long messageId, Long operatorId) {
        GroupMessage message = groupMessageMapper.selectById(messageId);
        if (message == null || message.getStatus() == 0) {
            throw new BaseException("消息不存在或已被撤回");
        }

        // 检查撤回权限（发送者本人或管理员可以撤回）
        if (!message.getSenderId().equals(operatorId)) {
            GroupMember operator = groupMemberMapper.selectByGroupAndUserId(message.getGroupId(), operatorId);
            if (operator == null || operator.getRole() < 1) {
                throw new BaseException("没有权限撤回该消息");
            }
        }

        // 检查撤回时间限制（普通成员只能撤回2分钟内的消息）
        GroupMember operator = groupMemberMapper.selectByGroupAndUserId(message.getGroupId(), operatorId);
        if (operator.getRole() == 0 &&
                message.getSendTime().plusMinutes(2).isBefore(LocalDateTime.now())) {
            throw new BaseException("消息发送超过2分钟，无法撤回");
        }

        groupMessageMapper.updateStatus(messageId, 0);
    }

    private GroupMessageVO convertToVO(GroupMessage message) {
        if (message == null) {
            return null;
        }
        GroupMessageVO vo = new GroupMessageVO();
        BeanUtils.copyProperties(message, vo);

        if (message.getSender() != null) {
            vo.setSenderName(message.getSender().getNickname());
            vo.setSenderAvatar(message.getSender().getAvatar());
        }

        return vo;
    }
}